import java.util.HashSet;

/**
 * @Description:水果成篮 https://leetcode.cn/problems/fruit-into-baskets/
 * @Date:Create in 10:38  2022/6/8
 */
public class totalFruit0904 {
    public static void main(String[] args) {
        int[] fruits = new int[]{3,3,3,1,2,1,1,2,3,3,4};
        System.out.println(totalFruit1(fruits));
    }

    //滑动窗口 三指针
    /*我们需要在遍历fruits,索引为j时,不断更新以下三个指针:
    当下的两个篮子第一个篮子起始索引first,
    当下的两个篮子第二个篮子起始索引second,
    未来的两个篮子第一个篮子的起始索引temp,
    计算两个篮子中i - first + 1的最大值即可求出水果最大长度len*/
    public static int totalFruit1(int[] fruits) {
        int sublength = 0;
        int first = 0;
        int second = 0;
        int temp = 0;

        HashSet<Integer> set = new HashSet<>();
        for (int j = 0; j < fruits.length; j++) {
            if (fruits[j] != fruits[first] && fruits[j] != fruits[second]) {
                if (first != second) {
                    first = temp;
                }
                second = j;
            }
            sublength = Math.max(sublength, j - first + 1);
            if (fruits[temp] != fruits[j]) {
                temp = j;
            }
            System.out.println(temp);
        }
        return sublength;
    }
}
